package com.zjw.job;


import com.zjw.constants.SystemConstants;
import com.zjw.annotation.domain.entity.Article;
import com.zjw.service.ArticleService;
import com.zjw.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class UpdateViewCountJob {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ArticleService articleService;

//    @Scheduled(cron = "*/10 * * * * *") // 每十秒执行一次
    @Scheduled(cron = "0 */10 * * * ?")   // 每十分钟执行一次
    private void updateViewCountJob(){
//        获取Redis中的浏览量map
        Map<String, Integer> cacheMap = redisCache.getCacheMap(SystemConstants.REDIS_VIEW_COUNT_KEY);

        List<Article> res = cacheMap.entrySet().stream()
                .map((entry) -> {
                    Article article = new Article();
                    article.setId(Long.parseLong(entry.getKey()));
                    article.setViewCount(Long.valueOf(entry.getValue()));
                    return article;
                }).collect(Collectors.toList());
//        将它更新到数据库
        articleService.updateBatchById(res);
    }

}
